package com.stormrage.edu.ctrl.edu;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSON;
import com.stormrage.constants.ErrCons;
import com.stormrage.edu.serv.adm.AdmAcctServ;
import com.stormrage.edu.serv.edu.EduMajorServ;
import com.stormrage.edu.serv.edu.EduProjectServ;
import com.stormrage.edu.serv.edu.view.EduProjectMajorServ;
import com.stormrage.entity.adm.AdmRes;
import com.stormrage.entity.edu.EduProject;
import com.stormrage.entity.edu.rep.EduMajorRep;
import com.stormrage.entity.edu.req.EduMajorReq;
import com.stormrage.entity.edu.req.EduProjectReq;
import com.stormrage.entity.edu.view.EduProjectMajor;
import com.stormrage.entity.rep.ErrorRep;
import com.stormrage.entity.rep.JsonRep;
import com.stormrage.entity.rep.ListRep;
import com.stormrage.entity.shiro.ShiroAcct;
import com.stormrage.shiro.bind.CurrentUser;
import com.stormragetech.core.ctrl.BaseCtrl;
import com.stormragetech.core.entity.Page;
import com.stormragetech.core.exception.StormrageTechException;

/**
 * @author www.stormragetech.com
 * @date 2016年1月19日
 * @version 1.0.0
 */
@Controller
@RequestMapping("/proj")
public class EduProjectCtrl extends BaseCtrl {

	private static final Logger logger = LoggerFactory.getLogger(EduProjectCtrl.class);

	@Value("#{constants['html.title']}")
	private String htmlTitle;

	@Value("#{constants['path.root']}")
	private String rootPath;

	@Value("#{constants['url.root']}")
	private String rootUrl;

	@Value("#{constants['path.image']}")
	private String imagePath;

	@Value("#{constants['path.ckeditor']}")
	private String ckeditorPath;

	@Autowired
	private AdmAcctServ admAcctServ;

	@Autowired
	private EduMajorServ eduMajorServ;

	@Autowired
	private EduProjectServ eduProjectServ;

	@Autowired
	private EduProjectMajorServ eduProjectMajorServ;

	@RequiresPermissions("proj:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(@CurrentUser ShiroAcct curr, Model model) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Create 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Create 】-【 GET 】- 结束运行 ");
		return "edu/proj/create";

	}

	@RequiresPermissions("proj:create")
	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@CurrentUser ShiroAcct curr, EduProject req, HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Create 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		if (null == file) {

			StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "添加项目失败，图片不能为空",
					StormrageTechException.ERR_APP, "【 EduProjectCtrl 】-【 Create 】");

			err = ErrorRep.instance(false, exception.getMessage());
			redirect.addFlashAttribute("err", err);

			return "redirect:/proj/list";

		}

		try {

			// ------------------ 上传图片操作 ------------------

			String path = rootPath + imagePath;
			String fileName = eduProjectServ.upload(file, path);
			req.setImage(fileName);
			req.setThumb(fileName);

			// ------------------ 创建项目操作 ------------------

			Integer index = eduProjectServ.create(req);
			errMsg = "提示信息：添加编号为【 " + index + " 】项目成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：添加项目失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/proj/list";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Create 】-【 POST 】- 结束运行 ");
		return "redirect:/proj/list";

	}

	@RequiresPermissions("proj:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String edit(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			EduProject entity = eduProjectServ.queryById(id);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("data", entity);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/proj/edit";

	}

	@RequiresPermissions("proj:edit")
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
	public String edit(@CurrentUser ShiroAcct curr, EduProject req,
			@RequestParam(value = "file", required = false) MultipartFile file, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			if (null != file && file.getBytes().length > 0) {
				String path = rootPath + imagePath;
				String fileName = eduProjectServ.upload(file, path);
				req.setImage(fileName);
				req.setThumb(fileName);
			}

			// ------------------ Ctrl操作 ------------------
			eduProjectServ.update(req);
			errMsg = "提示信息：修改编号为【 " + req.getId() + " 】项目成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：修改项目失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/proj/list";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 POST 】- 结束运行 ");
		return "redirect:/proj/list";

	}

	@RequiresPermissions("proj:del")
	@RequestMapping(value = "/del/{id}", method = RequestMethod.GET)
	public String delete(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Delete 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduProjectServ.delete(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】项目成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除课组失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/proj/list";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Delete 】-【 GET 】- 结束运行 ");
		return "redirect:/proj/list";

	}

	@RequiresPermissions("proj:view")
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(@CurrentUser ShiroAcct curr, EduProjectReq req, Model model) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 POST 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Edit 】-【 GET 】- 结束运行 ");
		return "edu/proj/list";
	}

	@RequiresPermissions("proj:view")
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, EduProjectReq req) {

		logger.debug(" 【 Controller 】- 【 EduProjectCtrl 】- 【 Ajax 】-【 POST 】-【 STARTED 】");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduProjectServ.queryList(req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduProjectCtrl 】- 【 Ajax 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("proj:add")
	@RequestMapping(value = "/list/{id}", method = RequestMethod.GET)
	public String list(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 List Major 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			List<EduMajorRep> array = eduMajorServ.queryRepListById(id);
			if (null != array && array.size() > 0)
				model.addAttribute("data", array);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 List Major 】-【 GET 】- 结束运行 ");
		return "edu/proj/major/list";

	}

	@RequiresPermissions("proj:del")
	@RequestMapping(value = "/major/del/{cid}/{id}")
	public String deleteView(@CurrentUser ShiroAcct curr, @PathVariable("id") Integer id, RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 DeleteView 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			eduProjectMajorServ.deleteById(id);
			errMsg = "提示信息：删除编号为【 " + id + " 】的项目专业关联成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：删除【 " + id + " 】的项目专业关联失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/proj/list/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 DeleteView 】-【 GET 】- 结束运行 ");
		return "redirect:/proj/list/{cid}";

	}

	@RequiresPermissions("proj:add")
	@RequestMapping(value = "/major/add/{id}", method = RequestMethod.GET)
	public String list(@CurrentUser ShiroAcct curr, EduMajorReq req, @PathVariable("id") Integer id, Model model) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 List Major Except 】-【 GET 】- 开始运行 ");

		try {

			// ------------------ 获取用户操作的 Menu ------------------
			List<AdmRes> menus = admAcctServ.queryMenuById(Integer.valueOf(curr.getId()));

			// ------------------ Ctrl操作 ------------------
			String search = JSON.toJSONString(req);

			logger.debug(" 查询条件req变为search为 " + search);

			if (null != search && search.length() > 0)
				model.addAttribute("search", search);

			model.addAttribute("user", curr);
			model.addAttribute("menus", menus);
			model.addAttribute("htmlTitle", htmlTitle);

			model.addAttribute("form", req);
			model.addAttribute("id", id);

		} catch (Exception e) {
			model.addAttribute("err", e.getMessage());
			return "error/500";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "edu/proj/major/add";

	}

	@RequiresPermissions("proj:add")
	@RequestMapping(value = "/major/ajax/{id}", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String ajax(@RequestParam(value = "draw", required = true) Integer draw,
			@RequestParam(value = "start", required = true) Integer start,
			@RequestParam(value = "length", required = true) Integer length, @PathVariable("id") Integer id,
			EduMajorReq req) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Ajax Major 】-【 GET 】- 开始运行 ");

		String json = null;

		try {

			// ------------------ 获取初始化模块的状态 ------------------
			Page page = Page.instance(start, length, 1);
			req.setPage(page);
			draw += 1;

			logger.debug(" 分页信息为 " + page.toString());

			ListRep entity = eduMajorServ.queryList(id, req);

			JsonRep rep = JsonRep.instance(entity.getCount(), draw, entity.getList());
			json = JSON.toJSONString(rep);

		} catch (Exception e) {
			return "error/500";
		}

		logger.debug(" 返回的json为 " + json);
		logger.debug(" 【 Controller 】- 【 EduProjectCtrl 】- 【 Ajax Major 】-【 POST 】-【 COMPLETED 】");
		return json;

	}

	@RequiresPermissions("proj:add")
	@RequestMapping(value = "/major/add/{cid}/{id}", method = RequestMethod.GET)
	public String add(@CurrentUser ShiroAcct curr, @PathVariable("cid") Integer cid, @PathVariable("id") Integer id,
			RedirectAttributes redirect) {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Add 】-【 GET 】- 开始运行 ");

		ErrorRep err = null;
		String errMsg = "";

		try {

			// ------------------ Ctrl操作 ------------------
			EduProjectMajor entity = EduProjectMajor.instance(cid, id);
			eduProjectMajorServ.create(entity);

			errMsg = "提示信息：编号为【 " + cid + " 】的项目关联编号为【 " + id + " 】的专业成功";
			err = ErrorRep.instance(true, errMsg);
			redirect.addFlashAttribute("err", err);

		} catch (Exception e) {
			errMsg = "提示信息：编号为【 " + cid + " 】的项目关联编号为【 " + id + " 】的专业失败";
			err = ErrorRep.instance(false, errMsg);
			redirect.addFlashAttribute("err", err);
			return "redirect:/proj/major/add/{cid}";
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Add 】-【 GET 】- 结束运行 ");
		return "redirect:/proj/major/add/{cid}";

	}

	@RequiresPermissions("proj:view")
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@CurrentUser ShiroAcct curr,
			@RequestParam(value = "upload", required = false) MultipartFile file, HttpServletRequest request,
			HttpServletResponse response, @RequestParam("CKEditorFuncNum") String callback) throws IOException {

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Upload 】-【 POST 】- 开始运行 ");

		try {

			PrintWriter out = response.getWriter();

			if (null == file) {

				StormrageTechException exception = StormrageTechException.instance(ErrCons.CTRL_ERR, "上传文件不能为空",
						StormrageTechException.ERR_APP, "【 EduProjectCtrl 】-【 Upload 】");

				out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'"
						+ exception.getMessage() + "');");
				out.println("</script>");
				return null;
			}

			// ------------------ 上传图片操作 ------------------

			String path = rootPath + ckeditorPath;
			String url = rootUrl + ckeditorPath + File.separator;
			String fileName = eduProjectServ.upload(file, path);
			out.println("<script type=\"text/javascript\">");
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + url + fileName + "','')");
			out.println("</script>");

		} catch (Exception e) {
			PrintWriter out = response.getWriter();
			out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'CKEditor上传图片失败');");
			out.println("</script>");
			return null;
		}

		logger.debug(" 【 Controller 】-【 EduProjectCtrl 】-【 Upload 】-【 POST 】- 结束运行 ");
		return null;
	}

}